import 'package:bot_toast/bot_toast.dart';
import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../../widgets/scale/scale_numberpicker_wrapper.dart';
import 'push_top_edit_dialog.dart';

class PushTopSettingLogic extends GetxController {
  String? id;
  DynamicDataSource? dataSource;
  PushTopSettingLogic({this.id, this.dataSource = DynamicDataSource.Cave});
  static int intervalTitleId = 1;
  static const int intervalScale = 10;

  //使用数量
  TextEditingController countController = TextEditingController(text: '1');

  //间隔时长
  String interval = '5.0';

  final GlobalKey<ScaleNumberPickerWrapperState> pickerKey =
      GlobalKey<ScaleNumberPickerWrapperState>();
  int cardCount = 0;
  @override
  void onInit() {
    super.onInit();
    getCard();
  }

  getCard() {
    WhlApi.getTopNum.post({}).then((value) {
      if (value.isSuccess()) {
        if (value.data != null) {
          cardCount = value.data['count'] ?? 0;
        }
        update();
      }
    });
  }

  ///时间间隔点击
  onTapInterval() {
    Get.dialog(PushTopEditDialog(
      interval: interval,
      onTap: (String s) {
        interval = double.parse(s).toStringAsFixed(1);
        update();
        pickerKey.currentState?.select(double.parse(s));
      },
    ));
  }

  onUpdateIntervalTitle(String s) {
    interval = s;
    update([intervalTitleId]);
  }

  ///提交
  onCommit() async {
    // if (countController.text.isEmpty) {
    //   BotToast.showText(text: "请输入使用数量");
    //   return;
    // }
    // int num = int.tryParse(countController.text) ?? 0;
    // if (num > cardCount) {
    //   MyToast.show('推顶卡数量不够');
    //   return;
    // }
    if (id != null) {
      //  从广场等地方进入
      var result;
      switch (dataSource) {
        case DynamicDataSource.Cave:
          result = await WhlApi.editCavTopOrder.post({
            'postId': id,
            'num': 1,
          });
          break;
        case DynamicDataSource.Collection:
        case DynamicDataSource.Square:
        case null:
        default:
          result = await WhlApi.editTopOrder.post({
            'squareId': id,
            'num': 1,
          });
          break;
      }

      if (result.isSuccess()) {
        MyToast.show('推顶成功');
        Get.back(result: {
          'num': countController.text,
        });
      } else {
        Get.back(result: '推顶失败');
      }
    } else {
      Get.back(result: {
        'num': countController.text,
      });
    }
  }
}
